package com.huanhong.hik.socket;

import cn.hutool.core.thread.ThreadUtil;
import com.huanhong.hik.service.DeviceService;
import io.socket.client.IO;
import io.socket.client.Socket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.URISyntaxException;

/**
 * @author zhls1
 */
@Slf4j
@Component
@EnableConfigurationProperties(SocketIoClientProperties.class)
public class SocketIoClient {

    private final SocketIoClientProperties socketIoClientProperties;

    public SocketIoClient(SocketIoClientProperties socketIoClientProperties) {
        this.socketIoClientProperties = socketIoClientProperties;
    }

    public static Socket socket;

    private void init() {
        init(null);
    }

    private void init(SocketIoClientProperties clientProperties) {
        if (null == clientProperties) {
            clientProperties = socketIoClientProperties;
        }
        String url = clientProperties.getProtocol() + "://" + clientProperties.getHost() + ":" + clientProperties.getPort();
        IO.Options options = new IO.Options();
        options.transports = clientProperties.getTransports();
        options.reconnectionAttempts = clientProperties.getReconnectionAttempts();
        options.reconnectionDelay = clientProperties.getReconnectionDelay();
        options.timeout = clientProperties.getTimeout();
        try {
            socket = IO.socket(url, options);
        } catch (URISyntaxException e) {
            log.error("Socket IO URISyntaxException:", e);
            return;
        }
        socket.connect();
        EventHandler.handle(socket);
    }

    @PostConstruct
    public void run() {
        log.info("SocketIOClient run!");
        ThreadUtil.execute(this::init);
    }

}
